package com.kckj.comm.util;

import org.apache.commons.io.output.ByteArrayOutputStream;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

public class PicUtils {

   /**
    * 描述:  从网址获取网络图片
    *
    * @return BASE64
    * @Param imgUrl
    * @author 代文杰
    * @version V1.0
    * @Date
    */
   public static byte[] getImageFromNetByUrl(String strUrl){
      try {
         URL url = new URL(strUrl);
         HttpURLConnection conn = (HttpURLConnection)url.openConnection();
         conn.setRequestMethod("GET");
         conn.setConnectTimeout(5 * 1000);
         InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
         byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
         return btImg;
      } catch (Exception e) {
         e.printStackTrace();
      }
      return null;
   }

   /**
    * 描述:  由于读取需要一定时间，所以不能单纯往字节数组里读，所以需要判断是否读完
    *
    * @return BASE64
    * @Param imgUrl
    * @author 代文杰
    * @version V1.0
    * @Date
    */
   public static byte[] readInputStream(InputStream inStream) throws Exception{ //存放读取的所有的字节数组
      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
      byte[] buffer = new byte[1024];
      int len = 0;
      while( (len=inStream.read(buffer)) != -1 ){
         outStream.write(buffer, 0, len);
      }
      inStream.close();
      return outStream.toByteArray();
   }

   /**
    * 描述:  将minio存储的jpg图片转为base64图片
    *
    * @return BASE64
    * @Param imgUrl
    * @author 代文杰
    * @version V1.0
    * @Date
    */
   public static String getImageStr(String imgUrl) {
      byte[] data = null;
      try {
         data =getImageFromNetByUrl(imgUrl);;
      } catch (Exception e) {
         e.printStackTrace();
      }
      return "data:image/jpg;base64," + Base64.getEncoder().encodeToString(data);
   }

}